<?php

/**
 * accessToken授权
 */
class AuthController extends ControllerBase {

    /**
     * 过期时间（秒）
     * @var int
     */
    private $expire = 7200;

    /**
     * 获取Accesstoken [GET]
     * @param string $appSecret
     * @example 接口请求地址：/auth/accesstoken/ + $appSecret
     * @example 返回结果：{"retcode":0,"retmsg":{"access_token":"b433de3ac626a1f54766e131deb983488ed7e8e3","expire_at":1446820446}}
     * @example 可用的$appSecret：eUGhdvpDDpC16iUXqfMsc3ntl , 0wtcDflIXFLHx4VJ3G32cuFGg , ghrF59N53zchmGO2KsWlWuokC
     * @example 请注意：在所有的API接口调用，URL后面必须追加?token=$accesstoken
     */
    public function accessTokenAction($appSecret = '') {
        if (!empty($appSecret)) {
            $keys = include __DIR__ . '/../config/appkeys.php';
            if (in_array($appSecret, $keys)) {
                $redis = mRedis::get_instance();
                if ($redis) {
                    $redisKey = 'auth-accesstoken';
                    $accessToken = $redis->get($redisKey);
                    if (!$accessToken) {
                        $accessToken = sha1($appSecret . uniqid() . time());
                        $redis->set($redisKey, $accessToken);
                        $redis->expire($redisKey, $this->expire);
                    }
                    if ($accessToken) {
                        $this->echoMsg(0, array(
                            'access_token' => $accessToken,
                            'expire_at' => (string)$redis->ttl($redisKey) + time(),
                            'expire_at2' => date('Y-m-d H:i:s', $redis->ttl($redisKey) + time()),
                        ));
                    } else {
                        $this->echoErrcode(ErrorCode::$ERR_TOKEN_ILLEGAL);
                    }
                }
            } else {
                $this->echoErrcode(ErrorCode::$ERR_APPSECRT_ILLEGAL);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_APPSECRT_ILLEGAL);
        }
    }

}
